package com.useeinfo.oa.modules.security.biz;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.AnalysisObjectList;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.ResultJson;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.security.dao.SystemRoleDao;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemRole;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.entity.UserRoleEnterprise;
import com.useeinfo.oa.modules.security.enums.OperationRoleEnum;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.security.vo.TreeSelectVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: 居泽平
 */
@Service("systemRoleBizWeb")
public class SystemRoleBiz extends CrudBiz<SystemRoleDao, SystemRole> {

    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private UserRoleEnterpriseBiz userRoleEnterpriseBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;

    public Boolean existRoleName(SystemRole systemRole) {
        //若角色名为空
        logger.info("角色名为：" + systemRole.getRoleName());
        if (StringUtils.isBlank(systemRole.getRoleName())) {
            return true;
        }

        //根据角色名查询
        QueryParam queryParam = new QueryParam();
        Enterprise enterprise = CommonSugar.getTypedDefault(systemRole.getEnterprise(), new Enterprise());
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        queryParam.getSqlMap().put("roleName", systemRole.getRoleName());
        List<SystemRole> systemRoleList = findList(queryParam);

        if (systemRole.getId() == null) {
            //新增操作，判断列表size是否为0
            return CollectionUtils.isNotEmpty(systemRoleList);
        } else {
            //修改操作，情况一：判断list长度是否为1，并且与自身相同，那么就是不存在，所以结果取反
            //修改操作，情况二：判断list长度是0
            return !((systemRoleList.size() == 1 && systemRoleList.get(0).getId().equals(systemRole.getId())) || systemRoleList.size() == 0);
        }
    }

    public List<SystemRole> findByAuthorityId(Long authorityId) {

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("existsAuthorityId", authorityId == null ? "-1" : authorityId.toString());

        return findList(queryParam);
    }

    @Transactional
    public Map<String, Object> getRoleAndAuthById(Long roleId) {

        Map<String, Object> map = new HashMap<>();
        SystemRole systemRole = findModel(roleId);
        List ownAuth = systemAuthorityBiz.getAuthoritiesByRoleId(roleId);
        List otherAuth = systemAuthorityBiz.getOtherAuthoritiesByRoleId(roleId);
        map.put("role", systemRole);
        map.put("ownAuth", ownAuth);
        map.put("otherAuth", otherAuth);
        return map;
    }

    @Transactional
    public SystemAuthority deleteAuthoritiesFromRoles(Long roleId, Long authId) {
        SystemAuthority systemAuthority = systemAuthorityBiz.findModel(authId);
        SystemRole systemRole = findModel(roleId);
        systemRole.removeAuthority(systemAuthority);
        return systemAuthority;
    }

    @Transactional
    public SystemAuthority addAuthoritiesToRoles(Long roleId, Long authId) {
        SystemAuthority systemAuthority = systemAuthorityBiz.findModel(authId);
        SystemRole systemRole = findModel(roleId);
        systemRole.addAuthority(systemAuthority);
        return systemAuthority;
    }

    @Transactional
    public JSONObject addOrRemoveAuthFromRole(Long roleId, Long authId, String type) {
        SystemAuthority systemAuthority = systemAuthorityBiz.findModel(authId);
        SystemRole systemRole = findModel(roleId);
        if (systemAuthority == null || systemRole == null || StringUtils.isBlank(type)) {
            return ResultJson.Error("失败");
        }
        if ("1".equals(type)) {//删除
            systemRole.removeAuthority(systemAuthority);
        } else {//新增
            systemRole.addAuthority(systemAuthority);
        }
        return ResultJson.OK();
    }

    @Transactional
    public JSONObject maneyAddOrRemoveAuth(Long roleId, List<Long> authArray, String type) {
        SystemRole systemRole = findModel(roleId);
        if (systemRole == null || StringUtils.isBlank(type) || CollectionUtils.isEmpty(authArray)) {
            return ResultJson.Error("失败");
        }
        for (Long id : authArray) {
            SystemAuthority systemAuthority = systemAuthorityBiz.findModel(id);
            if ("1".equals(type)) {//删除
                systemRole.removeAuthority(systemAuthority);
            } else {//新增
                systemRole.addAuthority(systemAuthority);
            }
        }
        return ResultJson.OK();
    }

    /**
     * 删除权限
     *
     * @param roleId
     */
    public void removeAuth(Long roleId) {
        if (roleId == null) {
            return;
        }
        dao.deleteAuthByRoleId(roleId);
    }

    /**
     * 添加权限
     *
     * @param roleId
     */
    public void addAuth(Long roleId, List<String> treesData) {
        if (CollectionUtils.isNotEmpty(treesData)) {
            SystemRole systemRole = findModel(roleId);
            treesData.forEach(authId -> {
                SystemAuthority systemAuthority = systemAuthorityBiz.findModel(StringConverters.ToLong(authId));
                if (systemAuthority != null)
                    systemRole.addAuthority(systemAuthority);
            });
        }
    }

    /**
     * 获取角色所有的权限
     *
     * @param roleId
     * @return
     */
    public List<TreeSelectVO> getAuthByRoleId(Long roleId, String sysCode) {
        List<TreeSelectVO> treeSelectVOS = new ArrayList<>();
        if (roleId != null) {
            List objects = dao.getAuthByRoleId(roleId);
            if (CollectionUtils.isNotEmpty(objects)) {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    treeSelectVOS.add(new TreeSelectVO(sysCode, AnalysisObjectList.getJsonString(j, 0)));
                }
            }
        }
        return treeSelectVOS;
    }


    public List<SystemRole> hqlExcute(String hql) {
        return dao.hqlExcute(hql);
    }

    /**
     * 批量修改角色
     *
     * @param organization 部门
     * @param position     岗位
     * @param role         角色
     */
    @Transactional
    public ResultDto changeRoleBatch(Organization organization, Position position, SystemRole role, Enterprise enterprise) {
        if (organization == null && position == null) {
            return ResultUtil.error("请选择需要更换的部门或岗位！");
        }
        if (role == null) {
            return ResultUtil.error("请选择角色！");
        }
        if (organization != null&&position==null) {//更新所有部门用户的角色
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
            queryParam.getSqlMap().put("organizations", organization.getId() + "");
            List<UserRoleEnterprise> userRoleEnterprises = userRoleEnterpriseBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(userRoleEnterprises)) {
                userRoleEnterprises.forEach(userRoleEnterprise -> userRoleEnterpriseBiz.delete(userRoleEnterprise.getId()));
            }
            QueryParam queryParam1 = new QueryParam();
            queryParam1.getSqlMap().put("enterpriseIds", enterprise.getId() + "");
            queryParam1.getSqlMap().put("organizationIds", organization.getId() + "");
            List<SystemUser> systemUsers = systemUserBiz.findList(queryParam1);
            systemUsers.forEach(systemUser -> userRoleEnterpriseBiz.addOrUpdate(new UserRoleEnterprise(role, enterprise, systemUser)));

        }
        if (organization != null&&position != null) {//更新所有岗位用户的角色
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
            queryParam.getSqlMap().put("organizationIds", organization.getId() + "");
            queryParam.getSqlMap().put("positions", position.getId() + "");
            List<UserRoleEnterprise> userRoleEnterprises = userRoleEnterpriseBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(userRoleEnterprises)) {
                userRoleEnterprises.forEach(userRoleEnterprise -> userRoleEnterpriseBiz.delete(userRoleEnterprise.getId()));
            }
            QueryParam queryParam1 = new QueryParam();
            queryParam1.getSqlMap().put("enterpriseIds", enterprise.getId() + "");
            queryParam1.getSqlMap().put("positions", position.getId() + "");
            List<SystemUser> systemUsers = systemUserBiz.findList(queryParam1);
            systemUsers.forEach(systemUser -> userRoleEnterpriseBiz.addOrUpdate(new UserRoleEnterprise(role, enterprise, systemUser)));
        }
        return ResultUtil.success();
    }

}